// forked from whirlpower's forked from: Tiling
// forked from quqjp's Tiling
//	http://wonderfl.net/c/eLxe
package 
{
    /*
    * BitmapをやめてShapeにしてみた。
    * 構造理解のため、そぎ落とせるところはそぎ落としている。
    *
    * ※ 止まりません。
    */

    import flash.display.*;
    import flash.events.Event;
    
    public class BoxFitting extends Sprite
    {
        private var mapLogic:MapLogic;
        
        public function BoxFitting():void
        {
            mapLogic = new MapLogic( 45, 45, 10, 10 );
            addEventListener( Event.ENTER_FRAME, render );
        }
        
        private function render( e:Event ):void
        {
            addChild( mapLogic.create() );
        }
    }
}

import flash.display.*;
    
internal class MapLogic
{
    private var _map            :Array = [];
    private var gridW        :int;
    private var gridH        :int;
    private var tileMax        :int;
    private var tileScale    :int = 10;
    public  var emptyPos        :int = 0;
    
    public function MapLogic( gridW:int, gridH:int, tileMax:int, tileScale:int ):void
    {
        this.gridW        = gridH;
        this.gridH        = gridW;
        this.tileMax        = tileMax;
        this.tileScale    = tileScale;
		
		
    }
    
    public function create():Tile
    {
        var position        :int = -1;
        var emptyWidth    :int = 0;
        
        for ( var i:int = emptyPos; i < emptyPos + 500 ; i++ ){
            if ( !_map[i] && position == -1 ){
                position = i;
                emptyWidth++;
            } else if ( emptyWidth >= tileMax ){
                break;
            } else if ( !_map[i] && !( i % gridW == 0 && i != emptyPos ) ) {
                emptyWidth++;
            } else if ( position != -1 ) {
                break;
            }
        }
        var ww:int    = int( Math.random() * emptyWidth )+1;
        
        var p:int = position;
        for ( var yy:int = 0; yy < ww; yy++ ){
            for ( var xx:int = 0; xx < ww; xx++ ){
                _map[p] = 1;
                p++;
            }
            p += gridW - ww;
        }
        emptyPos = position + ww;
        
        var px:int = position % gridW * tileScale;
        var py:int = position == 0 ? 0 : int( position / gridW ) * tileScale;
            
        return new Tile( px, py, ww* tileScale, ww * tileScale );
    }
}

internal class Tile extends Shape
{
    public function Tile( _x:int, _y:int, _w:int, _h:int ):void
    {
        this.x = _x;
        this.y = _y;
        
        graphics.lineStyle( 1, 0x000000 );
        graphics.drawRect( 0, 0, _w, _h );
    }
}